//
//  CategoryPickerView.swift
//  MyDiary2025
//
//  Created by 罗万能 on 2025/6/27.
//

import SwiftUI

let noSelectedId: UUID = UUID()
struct CategoryPickerView: View {
    var categorys:[CategoryModel]
//    let noSelectedId = UUID()
  
    @Binding var selectedCategory: CategoryModel?
    @State var selectedCategoryId: UUID = noSelectedId
    var body: some View {
        ZStack(alignment: .center) {
            RoundedRectangle(cornerRadius: 12)
                .foregroundStyle(.back.opacity(0.3))
                .shadow(radius: 3)
//                
            Picker(selection: $selectedCategoryId) {
                Text("全部")
                    .tag(noSelectedId)
                ForEach(categorys){category in
                    Text(category.categoryName)
                        .tag(category.id)
                }
            } label: {
                Text("日记类别")
            }
            .pickerStyle(.menu)
            .padding()
            .onChange(of: selectedCategoryId) { oldValue, newValue in
                if newValue == noSelectedId{
                    selectedCategory = nil
                    print("all")
                }else{
                    selectedCategory = fetchCategory(by: newValue)
                    print("fetch")
                }
                print(selectedCategory?.id ?? "no ")
                print(selectedCategoryId)
            }

            
        }.onAppear {
            if selectedCategory == nil{
                self.selectedCategoryId = noSelectedId
            }else{
                self.selectedCategoryId = selectedCategory!.id
            }
        }
        .frame(width:.infinity, height: 50)
        
        
        
//        .background(.warning)
    }
    private func fetchCategory(by id:UUID) -> CategoryModel?{
        for category in categorys {
            if category.id == id{
                return category
            }
        }
        return nil
    }
        
}

#Preview {
    CategoryPickerView(categorys: CategoryModel.debugDatas, selectedCategory: .constant(CategoryModel.debugDatas[1]))
}
